package com.scaffold.commons.config;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

/**
 * @author wangjg
 * 
 * 系统配置,支持多个配置文件
 */
public class FileConfig2 extends AbstractConfig {
	private Properties settings = new Properties();
	private List<File> fileList = new ArrayList<File>();
	
	public FileConfig2(){}
	
	public void loadResource(String...paths) throws Exception {
		for(String path:paths){
			Class c = this.getClass();
			URL url = c.getResource(path);
			File file = new File(url.toURI());
			Properties properties = this.loadFile(file);
			this.settings.putAll(properties);
		}
	}
	
	protected Properties loadFile(File file) {
		this.fileList.add(file);
		Properties properties = new Properties();
		InputStream is = null;
		try {
			is = new FileInputStream(file);
			String fileaName = file.getName();
			int start = fileaName.lastIndexOf(".");
			if (fileaName.substring(start).toLowerCase().equals(".xml")) {
				properties.loadFromXML(is);
			} else {
				properties.load(is);
			}
		} catch (Exception e) {
			throw new RuntimeException("*load configuration error, filepath:"+file.getParent() ,e);
		}finally{
			try {
				if(is!=null)is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return properties;
	}

	public Properties getSettings() {
		return settings;
	}

	public String getString(String key) {
		if(settings==null){
			return null;
		}
		String value = settings.getProperty(key);
		if(value==null){
			if(key!=null && key.startsWith("{") && key.endsWith("}")){
				value = System.getProperty(key.substring(1, key.length()-1));
			}
		}
		return value;
	}

}